package com.ls.service.impl;

import com.ls.entity.Comment;
import com.ls.mapper.CommentMapper;
import com.ls.mapper.DiscussPostMapper;
import com.ls.service.CommentService;
import com.ls.util.CommunityConstant;
import com.ls.util.SensitiveFilter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ls
 * @date 2020/12/26
 **/
@Service
public class CommentServiceImpl implements CommentService, CommunityConstant {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private SensitiveFilter sensitiveFilter;

    @Resource
    private DiscussPostMapper discussPostMapper;

    @Override
    public List<Comment> queryCommentsByEntity(int entityType, int entityId, int startIndex, int pageSize) {
        return commentMapper.queryCommentsByEntity(entityType, entityId, startIndex, pageSize);

    }

    @Override
    public int queryCountByEntity(int entityType, int entityId) {
        return commentMapper.queryCountByEntity(entityType, entityId);
    }

    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    @Override
    public void addComment(Comment comment) {
        if (comment == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        //  转义html标签,过滤敏感词
        comment.setContent(sensitiveFilter.filter(HtmlUtils.htmlEscape(comment.getContent())));

        commentMapper.addComment(comment);

        // 更新帖子评论数量
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            int count = commentMapper.queryCountByEntity(comment.getEntityType(), comment.getEntityId());
            discussPostMapper.updateCommentCount(comment.getEntityId(), count);
        }

    }

    @Override
    public Comment queryCommentById(int id) {
        return commentMapper.queryCommentById(id);
    }
}
